import 'package:flutter/material.dart';
import 'res/listData.dart';
void main(){
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor:Colors.red,
      ),
      home: Scaffold(
        appBar: AppBar(
          title:const Text("Flutter ListView"),
        ),
        body: MyHomePageByBuider(),
      ),
    );
  }
}

//for循环创建Widget
class MyHomePageByFor extends StatelessWidget {
  const MyHomePageByFor({super.key});
  List<Widget> _initListItem(){
    List<Widget> list = [];
    for(int i = 0;i<20;i++){
      list.add(ListTile(
        title: Text("列表cell$i"),
      ));
    }
    return list;
  }
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: _initListItem()
    );
  }
}

//Map遍历创建Widget
class MyHomePageByMap extends StatelessWidget {
   MyHomePageByMap({super.key}){
     print(listData);
   }
  List<Widget> _initWithData(){
    var list = listData.map((value){
       return ListTile(
         leading: Image.network(value["imageUrl"]),
         title: Text(value["title"]),
         subtitle: Text(value["author"]),
       );
    });
    return list.toList();
    return [];
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: _initWithData(),
    );
  }
}

//使用builder遍历方式
class MyHomePageByBuider extends StatelessWidget {
  const MyHomePageByBuider({super.key});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: listData.length,
        itemBuilder: (context,index){
         return ListTile(
            leading: Image.network(listData[index]["imageUrl"]),
            title: Text(listData[index]["title"]),
           subtitle: Text(listData[index]["author"]),
          );
    });
  }
}

